package controllers

import (
	"encoding/json"
	"errors"
	"github.com/astaxie/beego"
	"gitee.com/lzqysoft/ims/libs/encrypt"
	// "strconv"
	"strings"
	"time"
	"gitee.com/lzqysoft/ims/models"
)

// ProdTypeController operations for ProdType
type ProdTypeController struct {
	CommonController
}

// URLMapping ...
func (c *ProdTypeController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
}

// Post ...
// @Title Post
// @Description create ProdType
// @Param	body		body 	models.ProdType	true		"body for ProdType content"
// @Success 201 {int} models.ProdType
// @Failure 403 body is empty
// @router / [post]
func (c *ProdTypeController) Post() {
	var v models.ProdType
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrNoData)
	}
	err = json.Unmarshal(rdata, &v)
	v.Isdelete = 0
	v.Status = 1
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Id = encrypt.GetGuid()
	_, err = models.AddProdType(&v)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)

	}
	c.Dlog("添加了产品类型", v.Id)
	rt := make(map[string]interface{})
	rt["Id"] = v.Id
	c.RetSuccess(rt)
}

// GetOne ...
// @Title Get One
// @Description get ProdType by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.ProdType
// @Failure 403 :id is empty
// @router /:id [get]
func (c *ProdTypeController) GetOne() {
	id := c.Ctx.Input.Param(":id")
	// id, _ := strconv.Atoi(idStr)
	v, err := models.GetProdTypeById(id)
	if err != nil {
		c.Data["json"] = err.Error()
	} else {
		c.Data["json"] = v
	}
	c.ServeJSON()
}

// GetAll ...
// @Title Get All
// @Description get ProdType
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.ProdType
// @Failure 403
// @router / [get]
func (c *ProdTypeController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	var query = make(map[string]string)
	var limit int64 = 10
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	query["Isdelete"] = "0"
	limit = -1
	l, err := models.GetAllProdType(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError( ErrDatabase)
	}
	tree := models.GetProdTypeTree()
	tabledata := make(map[string]interface{})
	tabledata["treedata"] = tree
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)

}

// Update ...
// @Title Put
// @Description update the ProdType
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.ProdType	true		"body for ProdType content"
// @Success 200 {object} models.ProdType
// @Failure 403 data is not vilidate
// @router /Update [post]
func (c *ProdTypeController) Update() {
	user := c.User
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	var v models.ProdType
	err = json.Unmarshal(rdata, &v)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrInputData)
	}
	u, _ := models.GetProdTypeById(v.Id)

	v.Updater = user.Name
	v.Utime = time.Now()
	err = models.UpdateProdTypeById(&v)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)
	}

	c.Dlog("修改了产品类型,产品id为：", v.Id, 1, u)
	c.RetSuccess(v.Id)

}

// Delete ...
// @Title Delete
// @Description delete the ProdType
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *ProdTypeController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError( ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError( ErrInputData)
	}

	err = models.SoftDeleteProdType(id, user.Name)
	if err != nil {
		beego.Error(err)
		c.RetError( ErrDatabase)
	}
	c.Dlog("删除了产品类型", id)
	c.RetSuccess(id)
}
